var typeUser = -1;
var arrayData = new Array;

function btnRegister_onclick()
{
    var argsArray=new Array();
    argsArray.push(newArg("action","add"));
    var txtID=document.getElementById("txtId").value;
    argsArray.push(newArg("id",txtID));
    var txtEmail=document.getElementById("txtMail").value;
    argsArray.push(newArg("mail",txtEmail));
    var txtName=document.getElementById("txtName").value;
    argsArray.push(newArg("name",txtName));
    var txtUName=document.getElementById("txtUName").value;
    argsArray.push(newArg("uname",txtUName));
    var txtTelephone=document.getElementById("txtTelephone").value;
    argsArray.push(newArg("telephone",txtTelephone));
    var txtPassword1=document.getElementById("txtPassword1").value;
    argsArray.push(newArg("password",hex_md5(txtPassword1)));
    var txtPassword2=document.getElementById("txtPassword2").value;
    var txtType=document.getElementById("userType");
    if(txtType != null){
        typeUser = 2;
        argsArray.push(newArg("type",txtType.value));
    }else
        argsArray.push(newArg("type",0));
    argsArray.join("&");

    if(txtID != "" && txtEmail!= "" && txtName!= "" && txtUName!= "" && txtTelephone!= "" && txtPassword1!= "" && txtPassword2!= "" && validarEmailFin()){
        if(txtPassword1==txtPassword2)
            sendRequest("../controller/register.jsp",argsArray,btnRegister_response);
        else
            jConfirm('Contraseñas no son iguales', 'Error', 'Error Dialog');
    }else
        jConfirm('Faltan datos por llenar o incorrectos','Error', 'Error Dialog');
    
}

function clear_fields(){
    document.getElementById("txtId").value="";
    document.getElementById("txtMail").value="";
    document.getElementById("txtName").value="";
    document.getElementById("txtUName").value="";
    document.getElementById("txtTelephone").value="";
    document.getElementById("txtPassword1").value="";
    document.getElementById("txtPassword2").value="";
    document.getElementById("userType").selectedIndex = 0;
}

function btnRegister_response()
{
    if (isValidResponse(this))
    {
        var res=this.responseText;
        if(res!="")
        {
            var info=eval("("+res+")");
            if(info.errorcode == 0){
                jAlert('Regitrado Correctamente','Ok', 'Success Dialog');
                clear_fields();
                if(typeUser == 2){
                    loadUsers();
                    typeUser = -1;
                }
            }
            else if(info.errorcode == -1)
                jConfirm('Error guardando datos','Error', 'Error Dialog');
            else if(info.errorcode == -3)
                jConfirm('Nombre de usuario o identificación ya existe','Error', 'Error Dialog');
            else
                jConfirm('Acceso Incorrecto','Error', 'Error Dialog');
        }
    }
}

var objUser = function(id,mail,name,uname,telephone,type){
    this.uId = id;
    this.uMail = mail;
    this.uName = name;
    this.uUName = uname;
    this.uTelephone = telephone;
    this.uType = type;
}

function loadUsers(){
    var argsArray=new Array();
    argsArray.push(newArg('action', 'listUsers'));
    argsArray.join("&");
    sendRequest("../controller/register.jsp",argsArray,showLoadUsers);
}

function showLoadUsers(){
    if (isValidResponse(this)){
        var res=this.responseText;
        if(res!=""){
            var info=eval("("+res+")");
            if(info.errorcode == 0){
                var tableData = document.getElementById("dataUsers");
                var codeHTML = "<table border=\"0\" id=\"tableResult\" class='tableData'>";
                codeHTML += "<tr id=\"rowMain\">";
                codeHTML += "<th><br/></th>";
                codeHTML += "<th>Identificaci&oacute;n</th>";
                codeHTML += "<th>Nombre</th>";
                codeHTML += "<th>Nombre de Usuario</th>";
                codeHTML += "</tr>";
                arrayData = new Array;
                for(var cont=0;cont<info.data.length;cont++){
                    codeHTML += "<tr class=\"rows\">";
                    codeHTML += "<td><input type=\"radio\" name=\"user\" value=\""+info.data[cont].user_uname+"\"/></td>";
                    codeHTML += "<td>" + info.data[cont].user_id + "</td>";
                    codeHTML += "<td>" + info.data[cont].user_name + "</td>";
                    codeHTML += "<td>" + info.data[cont].user_uname + "</td>";
                    codeHTML += "</tr>";
                    arrayData.push(new objUser(info.data[cont].user_id,info.data[cont].user_mail,info.data[cont].user_name,info.data[cont].user_uname,info.data[cont].user_telephone,info.data[cont].user_type));
                }
                codeHTML += "</table>";
                tableData.innerHTML = codeHTML;
            }else if(info.errorcode == -1)
                jConfirm('No se encontraron datos de Usuarios','Error', 'Error Dialog');
            else
                jConfirm('Acceso Incorrecto','Error', 'Error Dialog');
        }
    }
}

function loadUpdate(){
    var elem = document.getElementsByName("user");
    var rad_val = -1;
    for (var i=0; i < elem.length; i++){
        if (elem[i].checked){
            //rad_val = elem[i].value;
            rad_val = i;
        }
    }
    if(rad_val != -1){
        document.getElementById("txtId1").value = arrayData[rad_val].uId;
        document.getElementById("txtMail1").value = arrayData[rad_val].uMail;
        document.getElementById("txtName1").value = arrayData[rad_val].uName;
        document.getElementById("txtUName1").value = arrayData[rad_val].uUName;
        document.getElementById("txtTelephone1").value = arrayData[rad_val].uTelephone;
        document.getElementById("userType1").selectedIndex = arrayData[rad_val].uType;
    }else
        jConfirm('Debe seleccionar un usuario','Error', 'Error Dialog');
}

function btnUpdate_onclick()
{
    var argsArray=new Array();
    argsArray.push(newArg("action","update"));
    var txtID=document.getElementById("txtId1").value;
    argsArray.push(newArg("id",txtID));
    var txtEmail=document.getElementById("txtMail1").value;
    argsArray.push(newArg("mail",txtEmail));
    var txtName=document.getElementById("txtName1").value;
    argsArray.push(newArg("name",txtName));
    var txtUName=document.getElementById("txtUName1").value;
    argsArray.push(newArg("uname",txtUName));
    var txtTelephone=document.getElementById("txtTelephone1").value;
    argsArray.push(newArg("telephone",txtTelephone));
    var txtPassword1=document.getElementById("txtPassword3").value;
    var txtPassword2=document.getElementById("txtPassword4").value;
    var txtType=document.getElementById("userType1");
    argsArray.push(newArg("type",txtType.value));    

    if(txtID != "" && txtEmail!= "" && txtName!= "" && txtUName!= "" && txtTelephone!= "" && validarEmailFin()){
        if(txtPassword1!= "" || txtPassword2!= "" ){
            if(txtPassword1==txtPassword2){
                argsArray.push(newArg("password",hex_md5(txtPassword1)));
                argsArray.join("&");
                sendRequest("../controller/register.jsp",argsArray,btnUpdate_response);
            }else
                jConfirm('Contraseñas no son iguales', 'Error', 'Error Dialog');
        }else{            
            argsArray.join("&");
            sendRequest("../controller/register.jsp",argsArray,btnUpdate_response);
        }
    }else
        jConfirm('Faltan datos por llenar o incorrectos','Error', 'Error Dialog');

}

function btnUpdate_response()
{
    if (isValidResponse(this))
    {
        var res=this.responseText;
        if(res!="")
        {
            var info=eval("("+res+")");
            if(info.errorcode == 0){
                jAlert('Actulizado Correctamente','Ok', 'Success Dialog');
                loadUsers();
            }
            else if(info.errorcode == -1)
                jConfirm('Error actualizando datos','Error', 'Error Dialog');
            else
                jConfirm('Acceso Incorrecto','Error', 'Error Dialog');
        }
    }
}

function deleteUser(){
    var elem = document.getElementsByName("user");
    var rad_val = null;
    for (var i=0; i < elem.length; i++){
        if (elem[i].checked){
            rad_val = elem[i].value;
            //rad_val = i;
        }
    }

    if(rad_val != null){
        jConfirm('Está seguro que desea eliminar al usuario ' + rad_val + ' ?','Confirmar',
            function(r) {
                if(r){
                    var argsArray=new Array();
                    argsArray.push(newArg("action","delete"));
                    argsArray.push(newArg("user",rad_val));
                    argsArray.join("&");
                    sendRequest("../controller/register.jsp",argsArray,deleteUser_response);
                }
            });
    }else
        jConfirm('Debe seleccionar un usuario','Error', 'Error Dialog');
}

function deleteUser_response()
{
    if (isValidResponse(this))
    {
        var res=this.responseText;
        if(res!="")
        {
            var info=eval("("+res+")");
            if(info.errorcode == 0){
                jAlert('Usuario eliminado Correctamente','Ok', 'Success Dialog');
                loadUsers();
            }
            else if(info.errorcode == -1)
                jConfirm('Error eliminando usuario','Error', 'Error Dialog');
            else
                jConfirm('Acceso Incorrecto','Error', 'Error Dialog');
        }
    }
}